
#include "msgdecoder.h"
#include "package.h"
#include "messageutil.h"

MsgDecoder :: MsgDecoder()
{
	mQueue = new SP_BlockingQueue();
}

MsgDecoder :: ~MsgDecoder()
{
	for( ; NULL != mQueue->top(); ) {
		free( (void*)mQueue->pop() );
	}

	delete mQueue;
	mQueue = NULL;
}

int MsgDecoder :: decode( SP_Buffer * inBuffer )
{
	int ret = eMoreData;

	for( ; ; ) {
		char* data=(char*)inBuffer->getBuffer();
		size_t size=inBuffer->getSize();
		if(size<sizeof(PackageHeader)) break;
		if(data[0]!=PackageFlag || data[1]!=PackageFlag)
		{
			inBuffer->erase(1);
			continue;
		}
		PackageHeader header;
		header.read(data);
		if(header.bodysize+header.off>size) break;
		std::string type=MessageUtil::getType(data+header.off,header.bodysize);
		Message* msg=MessageUtil::parseFromArray(data+header.off,header.bodysize);
		inBuffer->erase(header.bodysize+header.off);
		mQueue->push( new Package(header,type,data,header.bodysize+header.off,MessagePtr(msg)) );
		ret = eOK;
	}

	return ret;
}

SP_BlockingQueue * MsgDecoder :: getQueue()
{
	return mQueue;
}